package com.yixin.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.entity.domain.JobOffice;
import com.yixin.hospital.entity.domain.User;
import com.yixin.hospital.entity.dto.req.joboffice.JobOfficeAddReqDTO;
import com.yixin.hospital.entity.dto.req.joboffice.JobOfficeEditReqDTO;
import com.yixin.hospital.enums.ResponseCodeEnum;
import com.yixin.hospital.service.JobOfficeService;
import com.yixin.hospital.mapper.JobOfficeMapper;
import com.yixin.hospital.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author 
* @description 针对表【job_office(科室表)】的数据库操作Service实现
* @createDate 2024-03-28 21:37:13
*/
@Service
public class JobOfficeServiceImpl extends ServiceImpl<JobOfficeMapper, JobOffice>
    implements JobOfficeService{

    @Resource
    UserService userService;

    @Override
    public ApiResult allList(Long userId) {
        if (Objects.isNull(userId)) return ApiResult.success(this.list());
        User user = userService.getById(userId);
        if (user.getJobOffice() != null) {
            List<Long> jobOfficeIdList = Arrays.asList(user.getJobOffice().split(",")).stream().map(Long::valueOf).collect(Collectors.toList());
            return ApiResult.success(this.list(new LambdaQueryWrapper<JobOffice>().in(JobOffice::getId, jobOfficeIdList)));
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult add(JobOfficeAddReqDTO jobOfficeAddReqDTO, String userName) {
        List<JobOffice> list = this.list(new LambdaQueryWrapper<JobOffice>().eq(JobOffice::getName, jobOfficeAddReqDTO.getName()));
        if (!CollectionUtils.isEmpty(list)) return ApiResult.error(ResponseCodeEnum.JOB_OFFICE_EXIST);
        JobOffice jobOffice = new JobOffice();
        jobOffice.setName(jobOfficeAddReqDTO.getName());
        jobOffice.setCreatedBy(userName);
        jobOffice.setUpdatedBy(userName);
        this.save(jobOffice);
        return ApiResult.success();
    }

    @Override
    public ApiResult edit(JobOfficeEditReqDTO jobOfficeEditReqDTO, String userName) {
        JobOffice jobOffice = new JobOffice();
        jobOffice.setId(jobOfficeEditReqDTO.getId());
        jobOffice.setName(jobOfficeEditReqDTO.getName());
        jobOffice.setCreatedBy(userName);
        jobOffice.setUpdatedBy(userName);
        this.updateById(jobOffice);
        return ApiResult.success();
    }
}




